package logic

import (
	"context"
	"fmt"
	"housing/models/mysql"
	"math/rand"

	"housing/houserpc/houserpc"
	"housing/houserpc/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type LoginLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LoginLogic {
	return &LoginLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *LoginLogic) Login(in *houserpc.LoginRequest) (*houserpc.LoginResponse, error) {
	// todo: add your logic here and delete this line

	var user mysql.User
	mysql.DB.Debug().Where("mobile=?", in.Mobile).Find(&user)
	//sms, _ := cache.Rdb.Get(l.ctx, "sendSms"+in.SmsCode).Result()
	//if sms != in.SmsCode {
	//	return nil, fmt.Errorf("短信验证码错误,请重新输入")
	//}

	if user.ID == 0 {
		user = mysql.User{

			Mobile:    in.Mobile,
			Password:  in.Password,
			Nickname:  fmt.Sprintf("房源用户_%d", rand.Intn(100000)),
			HeadImage: "https://cn.bing.com/images/search?q=%E9%BB%98%E8%AE%A4%E5%A4%B4%E5%83%8F&FORM=IQFRBA&id=E5E80050344E688E1EB01ACCDA37300A4927DA23",
		}

		mysql.DB.Debug().Create(&user)

	} else {
		if in.Password != user.Password {
			return nil, fmt.Errorf("密码错误,请重新输入")
		}
	}
	return &houserpc.LoginResponse{
		UserId: int64(user.ID),
	}, nil
}
